<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\model\CompanyWarehouse;
use app\common\model\RegionStore;
use app\common\model\SalesmanDealer;
use app\common\model\SalesmanStore;
use app\common\model\Store;
use app\common\traits\SearchTrait;
use app\company\model\CompanyWarehouseArea;
use app\company\model\CompanyWarehouseGoods;
use app\company\model\CompanyWarehouseLocation;
use app\common\model\DealerGoods as DealerGoodsModel;
use app\common\model\Dealer as DealerModel;
use app\company\model\DealerStore;
use think\App;
use think\db\Query;
use think\response\Json;

class Search extends CompanyController
{
    use SearchTrait;

    protected array  $get    = [];
    protected string $fields = '*';

    public function __construct(App $app)
    {
        parent::__construct($app);
        // 传递参数，字段严格按照数据库字段标准查询，特定字段需要特定处理
        $this->get = $this->request->get();
        // 搜索字段
        $this->fields = !empty($this->get['fields']) ? htmlspecialchars_decode($this->get['fields']) : '*';
    }


    /**
     * 门店列表
     */
    public function storeList(): Json
    {
        $sql = $this->model = new Store();
        [$limit, $where] = $this->buildSearchParams();
        $filter     = $where ? json_decode(htmlspecialchars_decode($this->get['filter']), true) : '{}';
        $whereFiled = [];
        if (!empty($filter['dealer_id'])) {
            $ids          = DealerStore::where('dealer_id', $filter['dealer_id'])->column('store_id');
            $whereFiled[] = ['id', 'in', $ids];
        }
        if (!empty($filter['salesman_id'])) {
            $ids          = SalesmanStore::where('salesman_id', $filter['salesman_id'])->column('store_id');
            $whereFiled[] = ['id', 'in', $ids];
        }
        if (!empty($filter['region_id'])) {
            $ids          = RegionStore::where('region_id', $filter['region_id'])->column('store_id');
            $whereFiled[] = ['id', 'in', $ids];
        }
        if (!empty($whereFiled)) {
            $sql = $sql->where($whereFiled);
        }
        $sql = $sql->where($this->defaultWhere)
                   ->with([
                                  'region' => function (Query $query)
                                  {
                                      $query->field('id,name');
                                  }
                          ])
                   ->field($this->fields)
                   ->order($this->sort);
        if (!empty($this->get['limit'])) {
            $list = $sql->paginate($limit);
        } else {
            $list = $sql->select();
        }
        return $this->success($list);
    }

    /**
     * 仓库列表
     */
    public function warehouseList(): Json
    {
        $sql = $this->model = new CompanyWarehouse();
        [$limit, $where] = $this->buildSearchParams();
        $sql = $sql->where($where)->where($this->defaultWhere)->field($this->fields);
        if (!empty($this->get['limit'])) {
            $list = $sql->paginate($limit);
        } else {
            $list = $sql->select();
        }
        $list->each(function ($item)
        {
            $item->area = $item->area()->select()->each(function ($area)
            {
                $area->area_location = $area->location()->select();
            });
        });
        return $this->success($list);
    }

    public function dealerWarehouseList(): Json
    {
        $sql         = $this->model = new CompanyWarehouse();
        $salesmanIds = (new SalesmanDealer())
                ->where('dealer_id', $this->get['dealer_id'])
                ->where('company_id', $this->companyId)
                ->column('salesman_id');
        // 查询type为1的和type为2并且salesman_id在salesmanIds中的仓库列表
        $list = $sql->field('id,name,type')
                    ->where('type', 1)
                    ->where('company_id', $this->companyId)
                    ->whereOr(function ($query) use ($salesmanIds)
                    {
                        $query->where('type', 2)->where('salesman_id', 'in', $salesmanIds);
                    }
                    )->select();
        return $this->success($list);
    }

    /**
     * 库区列表
     */
    public function warehouseAreaList(): Json
    {
        $sql = $this->model = new CompanyWarehouseArea();
        [$limit, $where] = $this->buildSearchParams();
        $sql = $sql->where($where)->where($this->defaultWhere)->field($this->fields);
        if (!empty($this->get['limit'])) {
            $list = $sql->paginate($limit);
        } else {
            $list = $sql->select();
        }
        $list->each(function ($item)
        {
            $item->location = $item->location()->select();
        });
        return $this->success($list);
    }

    /**
     * 库位列表
     */
    public function warehouseLocationList(): Json
    {
        $sql = $this->model = new CompanyWarehouseLocation();
        [$limit, $where] = $this->buildSearchParams();
        $sql = $sql->where($where)->where($this->defaultWhere)->field($this->fields);
        if (!empty($this->get['limit'])) {
            $list = $sql->paginate($limit);
        } else {
            $list = $sql->select();
        }
        return $this->success($list);
    }

    /**
     * 移动仓关联业务员
     */
    public function warehouseSalesmanList(): Json
    {
        $sql = $this->model = new CompanyWarehouse();
        [$limit, $where] = $this->buildSearchParams();
        $sql = $sql->where($where)
                   ->where($this->defaultWhere)
                   ->where('type', 2);
        //                   ->field($this->fields);
        if (!empty($this->get['limit'])) {
            $list = $sql->paginate($limit);
        } else {
            $list = $sql->select();
        }
        $list->each(function ($item)
        {
            $item->salesman = $item->salesman()->field('id,rename')->find();
            // 业务员对应经销商
            $dealerIds = $item->salesman ?
                    (new SalesmanDealer())->where('salesman_id', $item->salesman->id)->column('dealer_id') : '';
            if ($dealerIds) {
                $item->dealer = (new DealerModel())->whereIn('id', $dealerIds)->field('id,name')->select();
            } else {
                $item->dealer = [];
            }
        });
        return $this->success($list);
    }

}